package cn.platform.util;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import cn.platform.response.AResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {


        AResponse res = new AResponse();

        // 处理 NotLoginException
        if (ex instanceof NotLoginException) {
            res.setMessage("未登录");
            res.setCode(ErrorCode.INVALID_TOKEN);
        }
        // 处理 NotPermissionException
        else if (ex instanceof NotPermissionException) {
            res.setMessage("未授权");
            res.setCode(ErrorCode.UNAUTHORIZED);
        }
        // 处理 UncategorizedSQLException
        else if (ex instanceof UncategorizedSQLException) {
            SQLException sqlEx = ((UncategorizedSQLException) ex).getSQLException();
            if (sqlEx != null) {
                res.setMessage(sqlEx.getMessage());
                res.setCode(ErrorCode.SQL_ERR);
            } else {
                res.setMessage("数据库错误");
                res.setCode(ErrorCode.DATABASE_ERR);
            }
        }
        // 处理 SQLIntegrityConstraintViolationException
        else if (ex instanceof SQLIntegrityConstraintViolationException) {
            res.setMessage("数据错误");
            res.setCode(ErrorCode.SQL_ERR);
        }

        else {
            res.setMessage(ex.getMessage());
            res.setCode(ErrorCode.UNKNOWN_ERR);
        }

        try {
            // 设置响应头
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpStatus.OK.value()); // 保持原逻辑返回 200

            // 将 AResponse 序列化为 JSON 并写入响应
            objectMapper.writeValue(response.getWriter(), res);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回空的 ModelAndView 表示已处理
        return new ModelAndView();
    }
}
